package org.groupg.poi.word;

import cn.hutool.core.io.resource.ResourceUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

public class POITableInWordReader {
    public static void main(String[] args) {
        String filePath = "001.docx"; // 替换为你的文件路径

        // 读取 docx
        try (FileInputStream fis = new FileInputStream(ResourceUtil.getResource(filePath).getFile());
             XWPFDocument document = new XWPFDocument(fis)) {

            // 遍历段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                System.out.println("段落:");
                for (XWPFRun run : paragraph.getRuns()) {
                    System.out.println(run.getText(0));
                }
                System.out.println();
            }

            // 遍历表格
            List<XWPFTable> tables = document.getTables();
            for (XWPFTable table : tables) {
                System.out.println("表格:");
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        System.out.print("单元格: ");
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            for (XWPFRun run : paragraph.getRuns()) {
                                System.out.print(run.getText(0) + " ");
                            }
                        }
                        System.out.println();
                    }
                }
                System.out.println();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        String docFilePath = "001.doc";
        // 读取 .doc 文件
        FileInputStream fisDoc = null;
        try {
            fisDoc = new FileInputStream(ResourceUtil.getResource(docFilePath).getFile());
            HWPFDocument doc = new HWPFDocument(fisDoc);
            WordExtractor extractorDoc = new WordExtractor(doc);
            String docText = extractorDoc.getText();
//            extractorDoc
            fisDoc.close();
            System.out.println(".doc 文件内容:");
            System.out.println(docText);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
